package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.region.dto.ZoneQueryDTO;
import com.smart.community.region.dto.ZoneInfoUpdateDTO;
import com.smart.community.region.entity.Zone;
import com.smart.community.region.entity.ZoneBuilding;
import com.smart.community.region.entity.ZoneDrawing;
import com.smart.community.region.mapper.ZoneMapper;
import com.smart.community.region.mapper.ZoneBuildingMapper;
import com.smart.community.region.mapper.ZoneDrawingMapper;
import com.smart.community.region.vo.ZoneDetailVO;
import com.smart.community.region.vo.ZoneListVO;
import com.smart.community.region.vo.ZoneBuildingVO;
import com.smart.community.region.vo.ZoneDrawingVO;
import com.smart.community.region.service.IZoneService;
import com.smart.community.region.entity.Community;
import com.smart.community.region.service.ICommunityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.Objects;
import com.smart.community.region.vo.ZoneWithBuildingsVO;

/**
 * 分区服务实现类
 *
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class ZoneServiceImpl extends ServiceImpl<ZoneMapper, Zone> implements IZoneService {

    @Autowired
    private ZoneBuildingMapper zoneBuildingMapper;
    
    @Autowired
    private ZoneDrawingMapper zoneDrawingMapper;

    @Autowired
    private DataScopeFeign dataScopeFeign;
    
    @Autowired
    private ICommunityService communityService;

    @Override
    public IPage<Zone> getZonePage(Page<Zone> page, ZoneQueryDTO queryDTO) {
        long startTime = System.currentTimeMillis();
        log.info("分页查询分区列表，页码：{}，大小：{}，查询条件：{}", 
                page != null ? page.getCurrent() : null, 
                page != null ? page.getSize() : null, 
                queryDTO);
        
        // 参数验证
        if (page == null) {
            log.warn("分页参数不能为空");
            return null;
        }
        
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            
            LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
            
            // 构建查询条件
            if (queryDTO != null) {
                // 分区名称模糊查询
                if (StringUtils.hasText(queryDTO.getZoneName())) {
                    queryWrapper.like(Zone::getZoneName, queryDTO.getZoneName());
                }
                
                // 分区编码模糊查询
                if (StringUtils.hasText(queryDTO.getZoneCode())) {
                    queryWrapper.like(Zone::getZoneCode, queryDTO.getZoneCode());
                }
                
                // 社区ID精确查询
                if (queryDTO.getCommunityId() != null) {
                    queryWrapper.eq(Zone::getCommunityId, queryDTO.getCommunityId());
                }
                
                // 物业公司ID精确查询
                if (queryDTO.getPropertyCompanyId() != null) {
                    queryWrapper.eq(Zone::getPropertyCompanyId, queryDTO.getPropertyCompanyId());
                }
                
                // 分区类型精确查询
                if (StringUtils.hasText(queryDTO.getZoneType())) {
                    queryWrapper.eq(Zone::getZoneType, queryDTO.getZoneType());
                }
                
                // 状态精确查询
                if (queryDTO.getStatus() != null) {
                    queryWrapper.eq(Zone::getStatus, queryDTO.getStatus());
                }
            }
            
            // 默认只查询启用状态的分区
            queryWrapper.eq(Zone::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            // 应用数据权限过滤
            applyDataPermissionFilter(queryWrapper, currentUserId);
            
            // 按排序顺序和创建时间排序
            queryWrapper.orderByAsc(Zone::getSortOrder)
                       .orderByDesc(Zone::getCreateTime);
            
            IPage<Zone> result = this.page(page, queryWrapper);
            long endTime = System.currentTimeMillis();
            log.info("分页查询分区列表完成，页码：{}，大小：{}，结果数量：{}，耗时：{}ms", 
                    page.getCurrent(), page.getSize(), 
                    result != null ? result.getRecords().size() : 0, 
                    (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("分页查询分区列表失败，页码：{}，大小：{}，耗时：{}ms，错误：{}", 
                    page.getCurrent(), page.getSize(), (endTime - startTime), e.getMessage());
            return null;
        }
    }

    /**
     * 应用数据权限过滤
     * 
     * @param queryWrapper 查询条件包装器
     * @param currentUserId 当前用户ID
     */
    private void applyDataPermissionFilter(LambdaQueryWrapper<Zone> queryWrapper, Long currentUserId) {
        try {
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            
            // 超级管理员，不应用数据权限过滤
            if (userDataScope != null && userDataScope.isSuperAdmin()) {
                log.debug("用户{}为超级管理员，不应用数据权限过滤", currentUserId);
                return;
            }

            // 物业公司用户，只查询关联的社区
            if (userDataScope != null) {
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds != null && !communityIds.isEmpty()) {
                    queryWrapper.in(Zone::getCommunityId, communityIds);
                    log.debug("用户{}数据权限过滤完成，可访问社区数量：{}", currentUserId, communityIds.size());
                } else {
                    // 如果没有可访问的社区，返回空结果
                    queryWrapper.eq(Zone::getId, -1L);
                    log.debug("用户{}无权限访问任何社区数据", currentUserId);
                }
            } else {
                // 权限信息为空，返回空结果，确保数据安全
                queryWrapper.eq(Zone::getId, -1L);
                log.warn("用户{}权限信息为空，返回空结果", currentUserId);
            }
        } catch (Exception e) {
            log.warn("应用数据权限过滤失败，用户ID：{}，错误：{}", currentUserId, e.getMessage());
            // 权限验证失败时，返回空结果，确保数据安全
            queryWrapper.eq(Zone::getId, -1L);
        }
    }

    @Override
    @Cacheable(value = "zone:community", key = "'with-buildings:' + #communityId", unless = "#result == null || #result.isEmpty()")
    public List<ZoneWithBuildingsVO> getByCommunityId(Long communityId) {
        long startTime = System.currentTimeMillis();
        log.info("根据社区ID查询分区列表，社区ID: {}", communityId);
        
        // 参数验证
        if (communityId == null) {
            log.warn("社区ID不能为空");
            return Collections.emptyList();
        }
        
        try {
            LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Zone::getCommunityId, communityId)
                       .eq(Zone::getStatus, SystemStatusEnum.ENABLED.getCode())
                       .orderByDesc(Zone::getSortOrder);
            
            List<Zone> zones = this.list(queryWrapper);
            List<ZoneWithBuildingsVO> result = new ArrayList<>();
            
            // 为每个分区加载楼栋关联数据
            for (Zone zone : zones) {
                try {
                    ZoneWithBuildingsVO zoneWithBuildings = new ZoneWithBuildingsVO();
                    BeanUtils.copyProperties(zone, zoneWithBuildings);
                    
                    // 查询分区关联的楼栋
                    LambdaQueryWrapper<ZoneBuilding> buildingWrapper = new LambdaQueryWrapper<>();
                    buildingWrapper.eq(ZoneBuilding::getZoneId, zone.getId())
                                  .eq(ZoneBuilding::getStatus, SystemStatusEnum.ENABLED.getCode());
                    List<ZoneBuilding> zoneBuildings = zoneBuildingMapper.selectList(buildingWrapper);
                    
                    // 转换为楼栋VO列表
                    List<ZoneBuildingVO> buildingVOs = zoneBuildings.stream().map(building -> {
                        ZoneBuildingVO buildingVO = new ZoneBuildingVO();
                        BeanUtils.copyProperties(building, buildingVO);
                        return buildingVO;
                    }).collect(Collectors.toList());
                    
                    // 设置楼栋列表到分区对象中
                    zoneWithBuildings.setBuildings(buildingVOs);
                    
                    result.add(zoneWithBuildings);
                    
                    log.debug("分区 {} 关联楼栋数量: {}", zone.getId(), buildingVOs.size());
                } catch (Exception e) {
                    log.warn("加载分区 {} 的楼栋关联数据失败，错误: {}", zone.getId(), e.getMessage());
                    ZoneWithBuildingsVO zoneWithBuildings = new ZoneWithBuildingsVO();
                    BeanUtils.copyProperties(zone, zoneWithBuildings);
                    zoneWithBuildings.setBuildings(new ArrayList<>());
                    result.add(zoneWithBuildings);
                }
            }
            
            long endTime = System.currentTimeMillis();
            log.info("根据社区ID查询分区列表完成，社区ID: {}，分区数量: {}，耗时: {}ms", 
                    communityId, result.size(), (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据社区ID查询分区列表失败，社区ID: {}，耗时: {}ms，错误: {}", 
                    communityId, (endTime - startTime), e.getMessage());
            return Collections.emptyList();
        }
    }

    @Override
    @Cacheable(value = "zone:property", key = "'company:' + #propertyCompanyId", unless = "#result == null || #result.isEmpty()")
    public List<Zone> getByPropertyCompanyId(Long propertyCompanyId) {
        long startTime = System.currentTimeMillis();
        log.info("根据物业公司ID查询分区列表，物业公司ID: {}", propertyCompanyId);
        
        // 参数验证
        if (propertyCompanyId == null) {
            log.warn("物业公司ID不能为空");
            return Collections.emptyList();
        }
        
        try {
            LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Zone::getPropertyCompanyId, propertyCompanyId)
                       .eq(Zone::getStatus, SystemStatusEnum.ENABLED.getCode())
                       .orderByAsc(Zone::getSortOrder);
            
            List<Zone> result = this.list(queryWrapper);
            long endTime = System.currentTimeMillis();
            log.info("根据物业公司ID查询分区列表完成，物业公司ID: {}，结果数量: {}，耗时: {}ms", 
                    propertyCompanyId, result.size(), (endTime - startTime));
            
            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据物业公司ID查询分区列表失败，物业公司ID: {}，耗时: {}ms，错误: {}", 
                    propertyCompanyId, (endTime - startTime), e.getMessage());
            return Collections.emptyList();
        }
    }

    @Override
    @Cacheable(value = "zone:validation", key = "'code-exists:' + #zoneCode + ':' + #communityId + ':' + (#excludeId != null ? #excludeId : 'null')")
    public boolean isZoneCodeExists(String zoneCode, Long communityId, Long excludeId) {
        long startTime = System.currentTimeMillis();
        log.info("检查分区编码是否存在，编码: {}, 社区ID: {}, 排除ID: {}", zoneCode, communityId, excludeId);
        
        // 参数验证
        if (zoneCode == null || communityId == null) {
            log.warn("分区编码和社区ID不能为空");
            return false;
        }
        
        try {
            LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Zone::getZoneCode, zoneCode)
                       .eq(Zone::getCommunityId, communityId)
                       .eq(Zone::getStatus, SystemStatusEnum.ENABLED.getCode());
            
            if (excludeId != null) {
                queryWrapper.ne(Zone::getId, excludeId);
            }
            
            boolean exists = this.count(queryWrapper) > 0;
            long endTime = System.currentTimeMillis();
            log.info("检查分区编码是否存在完成，编码: {}, 社区ID: {}, 结果: {}，耗时: {}ms", 
                    zoneCode, communityId, exists, (endTime - startTime));
            
            return exists;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("检查分区编码是否存在失败，编码: {}, 社区ID: {}，耗时: {}ms，错误: {}", 
                    zoneCode, communityId, (endTime - startTime), e.getMessage());
            return false;
        }
    }

    @Override
    @CacheEvict(value = {"zone:page", "zone:community", "zone:property", "zone:validation"}, allEntries = true)
    public boolean saveBatchZones(List<Zone> zones) {
        long startTime = System.currentTimeMillis();
        log.info("批量保存分区，数量: {}", zones != null ? zones.size() : 0);
        
        // 参数验证
        if (zones == null || zones.isEmpty()) {
            log.debug("分区列表为空，无需保存");
            return true;
        }
        
        try {
            boolean result = this.saveBatch(zones);
            long endTime = System.currentTimeMillis();
            log.info("批量保存分区完成，数量: {}，结果: {}，耗时: {}ms", 
                    zones.size(), result, (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("批量保存分区失败，数量: {}，耗时: {}ms，错误: {}", 
                    zones.size(), (endTime - startTime), e.getMessage());
            return false;
        }
    }

    @Override
    @CacheEvict(value = {"zone:page", "zone:community", "zone:property", "zone:validation"}, allEntries = true)
    public boolean updateBatchZones(List<Zone> zones) {
        long startTime = System.currentTimeMillis();
        log.info("批量更新分区，数量: {}", zones != null ? zones.size() : 0);
        
        // 参数验证
        if (zones == null || zones.isEmpty()) {
            log.debug("分区列表为空，无需更新");
            return true;
        }
        
        try {
            boolean result = this.updateBatchById(zones);
            long endTime = System.currentTimeMillis();
            log.info("批量更新分区完成，数量: {}，结果: {}，耗时: {}ms", 
                    zones.size(), result, (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("批量更新分区失败，数量: {}，耗时: {}ms，错误: {}", 
                    zones.size(), (endTime - startTime), e.getMessage());
            return false;
        }
    }

    @Override
    @Cacheable(value = "zone:detail", key = "#id", unless = "#result == null")
    public ZoneDetailVO getZoneDetail(Long id) {
        long startTime = System.currentTimeMillis();
        log.info("查询分区详情，分区ID: {}", id);
        
        // 参数验证
        if (id == null) {
            log.warn("分区ID不能为空");
            return null;
        }
        
        try {
            // 查询分区基本信息
            Zone zone = this.getById(id);
            if (zone == null) {
                log.warn("分区不存在，分区ID: {}", id);
                return null;
            }
            
            // 数据权限验证
            if (!validateZonePermission(zone)) {
                log.warn("用户无权限访问分区，分区ID: {}", id);
                return null;
            }
            
            // 转换为VO
            ZoneDetailVO zoneDetailVO = new ZoneDetailVO();
            BeanUtils.copyProperties(zone, zoneDetailVO);
            
            // 查询分区关联的楼栋
            LambdaQueryWrapper<ZoneBuilding> buildingWrapper = new LambdaQueryWrapper<>();
            buildingWrapper.eq(ZoneBuilding::getZoneId, id)
                          .eq(ZoneBuilding::getStatus, SystemStatusEnum.ENABLED.getCode());
            List<ZoneBuilding> zoneBuildings = zoneBuildingMapper.selectList(buildingWrapper);
            
            // 转换为楼栋VO
            List<ZoneBuildingVO> buildingVOs = zoneBuildings.stream().map(building -> {
                ZoneBuildingVO buildingVO = new ZoneBuildingVO();
                BeanUtils.copyProperties(building, buildingVO);
                return buildingVO;
            }).collect(Collectors.toList());
            
            zoneDetailVO.setBuildings(buildingVOs);
            
            // 查询绘图数据
            LambdaQueryWrapper<ZoneDrawing> drawingWrapper = new LambdaQueryWrapper<>();
            drawingWrapper.eq(ZoneDrawing::getCommunityId, zone.getCommunityId())
                         .eq(ZoneDrawing::getIsCurrent, SystemStatusEnum.ENABLED.getCode());
            ZoneDrawing zoneDrawing = zoneDrawingMapper.selectOne(drawingWrapper);
            
            if (zoneDrawing != null) {
                ZoneDrawingVO drawingVO = new ZoneDrawingVO();
                BeanUtils.copyProperties(zoneDrawing, drawingVO);
                zoneDetailVO.setDrawingData(drawingVO);
            }
            
            long endTime = System.currentTimeMillis();
            log.info("查询分区详情成功，分区ID: {}，耗时: {}ms", id, (endTime - startTime));
            return zoneDetailVO;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("查询分区详情失败，分区ID: {}，耗时: {}ms，错误: {}", 
                    id, (endTime - startTime), e.getMessage());
            return null;
        }
    }

    @Override
    @CacheEvict(value = {"zone:page", "zone:community", "zone:property", "zone:detail", "zone:validation"}, allEntries = true)
    public boolean updateZoneInfo(Long id, ZoneInfoUpdateDTO dto, Long currentUserId) {
        long startTime = System.currentTimeMillis();
        log.info("更新分区基本信息，分区ID: {}, 分区名称: {}", id, dto != null ? dto.getZoneName() : null);
        
        // 参数验证
        if (id == null) {
            log.warn("分区ID不能为空");
            return false;
        }
        if (dto == null) {
            log.warn("更新数据不能为空");
            return false;
        }
        if (currentUserId == null) {
            log.warn("当前用户ID不能为空");
            return false;
        }
        
        try {
            // 查询分区信息
            Zone zone = this.getById(id);
            if (zone == null) {
                log.warn("分区不存在，分区ID: {}", id);
                return false;
            }
            
            // 数据权限验证
            if (!validateZonePermission(zone)) {
                log.warn("用户无权限更新分区，分区ID: {}", id);
                return false;
            }
            
            // 更新分区信息
            BeanUtils.copyProperties(dto, zone);
            zone.setUpdateBy(currentUserId);
            
            boolean result = this.updateById(zone);
            long endTime = System.currentTimeMillis();
            log.info("更新分区基本信息完成，分区ID: {}，结果: {}，耗时: {}ms", 
                    id, result, (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("更新分区基本信息失败，分区ID: {}，耗时: {}ms，错误: {}", 
                    id, (endTime - startTime), e.getMessage());
            return false;
        }
    }

    /**
     * 验证分区操作权限
     * 
     * @param zone 分区信息
     * @return true表示有权限，false表示无权限
     */
    private boolean validateZonePermission(Zone zone) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        try {
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            
            // 超级管理员，有权限
            if (userDataScope != null && userDataScope.isSuperAdmin()) {
                log.debug("用户{}为超级管理员，拥有所有权限", currentUserId);
                return true;
            }

            // 物业公司用户，检查是否有权限操作该社区的分区
            if (userDataScope != null) {
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds != null && !communityIds.isEmpty() && communityIds.contains(zone.getCommunityId())) {
                    log.debug("用户{}分区权限验证通过，分区ID: {}", currentUserId, zone.getId());
                    return true;
                } else {
                    log.warn("用户{}无权限操作社区{}的分区", currentUserId, zone.getCommunityId());
                    return false;
                }
            } else {
                log.warn("用户{}权限信息为空，拒绝访问", currentUserId);
                return false;
            }
        } catch (Exception e) {
            log.warn("分区权限验证失败，用户ID: {}, 分区ID: {}, 错误: {}", currentUserId, zone.getId(), e.getMessage());
            // 权限验证失败时，默认拒绝访问，确保安全性
            return false;
        }
    }

    @Override
    @Cacheable(value = "zone:list", key = "'property-company:' + #propertyCompanyIds", unless = "#result == null || #result.isEmpty()")
    public List<ZoneListVO> getZoneListByPropertyCompanyId(List<Long> propertyCompanyIds) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("根据物业公司ID查询分区列表（包含社区信息），物业公司ID: {}", propertyCompanyIds);
        
        // 参数验证
        if (propertyCompanyIds == null || propertyCompanyIds.size()==0) {
            log.warn("物业公司ID不能为空");
            return Collections.emptyList();
        }
        
        try {
            // 调用Mapper方法查询分区列表（包含社区信息）
        	LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
        	queryWrapper.in(Zone::getPropertyCompanyId, propertyCompanyIds);
        	queryWrapper.eq(Zone::getStatus, 1); // 只查询启用状态的分区
        	queryWrapper.eq(Zone::getDeleted, 0); // 只查询未删除的分区
//        	queryWrapper.orderByAsc(Zone::getSortOrder, Zone::getCreateTime); // 按排序顺序和创建时间排序
        	List<Zone> selectList = baseMapper.selectList(queryWrapper);
        	
        	// 把 List<Zone> 转成 List<ZoneListVO>
        	List<ZoneListVO> result = new ArrayList<>();
        	if (selectList != null && !selectList.isEmpty()) {
        	    // 获取所有社区ID
        	    Set<Long> communityIds = selectList.stream()
        	            .map(Zone::getCommunityId)
        	            .filter(Objects::nonNull)
        	            .collect(Collectors.toSet());
        	    
        	    // 批量查询社区信息
        	    Map<Long, String> communityNameMap = new HashMap<>();
        	    if (!communityIds.isEmpty()) {
        	        LambdaQueryWrapper<Community> communityQueryWrapper = new LambdaQueryWrapper<>();
        	        communityQueryWrapper.in(Community::getId, communityIds);
        	        communityQueryWrapper.eq(Community::getStatus, 1);
        	        communityQueryWrapper.eq(Community::getDeleted, 0);
        	        List<Community> communities = communityService.list(communityQueryWrapper);
        	        
        	        communityNameMap = communities.stream()
        	                .collect(Collectors.toMap(
        	                    Community::getId,
        	                    Community::getCommunityName,
        	                    (existing, replacement) -> existing
        	                ));
        	    }
        	    
        	    // 转换为ZoneListVO
        	    for (Zone zone : selectList) {
        	        ZoneListVO vo = new ZoneListVO();
        	        vo.setZoneId(zone.getId());
        	        vo.setZoneName(zone.getZoneName());
        	        vo.setZoneCode(zone.getZoneCode());
        	        vo.setCommunityId(zone.getCommunityId());
        	        vo.setPropertyCompanyId(zone.getPropertyCompanyId());
        	        vo.setZoneType(zone.getZoneType());
        	        vo.setZoneColor(zone.getZoneColor());
        	        vo.setZoneDescription(zone.getZoneDescription());
        	        vo.setStatus(zone.getStatus());
        	        vo.setSortOrder(zone.getSortOrder());
        	        
        	        // 设置社区名称
        	        String communityName = communityNameMap.get(zone.getCommunityId());
        	        vo.setCommunityName(communityName);
        	        
        	        // 设置显示名称：社区名 - 分区名
        	        if (communityName != null && !communityName.trim().isEmpty()) {
        	            vo.setDisplayName(communityName + " - " + zone.getZoneName());
        	        } else {
        	            vo.setDisplayName(zone.getZoneName());
        	        }
        	        
        	        result.add(vo);
        	    }
        	}
            
            long endTime = System.currentTimeMillis();
            log.info("根据物业公司ID查询分区列表完成，物业公司ID: {}，结果数量: {}，耗时: {}ms",  propertyCompanyIds, result != null ? result.size() : 0, (endTime - startTime));
            
            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据物业公司ID查询分区列表失败，物业公司ID: {}，耗时: {}ms，错误: {}",  propertyCompanyIds, (endTime - startTime), e.getMessage());
            // 生产环境优雅降级，返回空列表而不是抛出异常
            return Collections.emptyList();
        }
    }
}
